package com.grsu.phonestation.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.grsu.phonestation.domain.Client;
import com.grsu.phonestation.domain.User;
import com.grsu.phonestation.service.ClientService;

@Controller
@RequestMapping("/registration")
public class RegistrationController {

	@Autowired
	@Qualifier("clientServiceImpl")
	private ClientService clientService;

	@RequestMapping(value = { "/", " " }, method = RequestMethod.POST)
	public ModelAndView registration(
			@ModelAttribute("client") @Valid Client client,
			String repeatPassword, BindingResult result) {

		ModelAndView mav = new ModelAndView();

		RegistrationValidator validator = new RegistrationValidator();

		boolean loginBusy;
		boolean emailBusy;

		if (clientService.getUserByLogin(client.getLogin()) != null) {
			loginBusy = true;
		} else {
			loginBusy = false;
		}
		User userByEmail = clientService.getUserByEmail(client.getEmail());

		if (userByEmail != null) {
			emailBusy = true;
		} else {
			emailBusy = false;
		}

		validator.loginBusy(loginBusy);
		validator.emailBusy(emailBusy);
		validator.setRepeatPassword(repeatPassword);
		validator.validate(client, result);

		if (result.hasErrors()) {
			mav = new ModelAndView("registration");
			mav.addObject("result", result);
			
			return mav; 
		}

		clientService.addUser(client);

		mav = new ModelAndView("redirect:/login");

		return mav;
	}

	@RequestMapping(value = { "/", " " }, method = { RequestMethod.GET })
	public ModelAndView home(Model model) {

		ModelAndView mav = new ModelAndView();
		mav.addObject("registration", new User());
		mav.setViewName("registration");

		return mav;
	}

}
